<template>
	<view :style="{height:PhoneInfo.windowHeight + 'px',width:PhoneInfo.windowWidth + 'px'}">
		<mvBar :mysNavConfig="mysNavConfig" @onLeftClick="onLeftClick"></mvBar>
		<u-toast ref="uToast"></u-toast>
		<view class="page">
			<view class="saoma" @click="scanCode">
				<view class="saom">
					<view class="sao">
						<view class="sa"><uni-icons type="scan" size="35" color="#fff"></uni-icons>
						</view>
					</view>
				</view>
			</view>
			<u-form labelPosition="left" :model="sensorinfo" ref="form1">
				<u-form-item label="SN" labelWidth="33" borderBottom prop="id" ref="item1">
					<u-input fontSize="14px" border="none" v-model="sensorinfo.id" placeholder="请扫描传感器机身二维码或者直接输入SN">
					</u-input>
				</u-form-item>
				<u-form-item label="别名" borderBottom prop="name" ref="item2">
					<u-input border="none" v-model="sensorinfo.name" maxlength="20" placeholder="为传感器设置便于记忆的别名">
					</u-input>
				</u-form-item>
				<view v-if="show==false">
					<u-form-item label="设备" prop="equipmentname" borderBottom
						@click="equipmentshow = true;hideKeyboard()" ref="item3">
						<u--input v-model="sensorinfo.equipmentname" disabled disabledColor="#f2f5f9"
							placeholder="请选择设备" border="none">
						</u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item label="测点" prop="pointname" borderBottom @click="pointshow = true;hideKeyboard()"
						ref="item4">
						<u--input v-model="sensorinfo.pointname" disabled disabledColor="#f2f5f9" placeholder="请选择测点"
							border="none">
						</u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</view>
				<view v-else>
					<u-form-item label="设备" prop="equipmentname" borderBottom ref="item3">
						<u--input v-model="sensorinfo.equipmentname" disabled disabledColor="#f2f5f9"
							placeholder="请选择设备" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="测点" prop="pointname" borderBottom ref="item4">
						<u--input v-model="sensorinfo.pointname" disabled disabledColor="#f2f5f9" placeholder="请选择测点"
							border="none">
						</u--input>
					</u-form-item>
				</view>
				<!-- 设备 -->
				<u-picker closeOnClickOverlay :immediateChange='true' @cancel="equipmentshow = false"
					@confirm="equipmentconfirm" :show="equipmentshow" :columns="equipmentcolumns" keyName="name">
				</u-picker>
				<!-- 测点 -->
				<u-picker closeOnClickOverlay :immediateChange='true' @cancel="pointshow = false"
					@confirm="pointconfirm" :show="pointshow" :columns="pointcolumns" keyName="name"></u-picker>
			</u-form>
			<view class="button">
				<u-button shape='circle' color="linear-gradient(to right, rgb(41, 121, 255), rgb(41, 121, 255))"
					type="primary" text="确定" @click="add">
				</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				mysNavConfig: {
					/* 占位开启  */
					navPadding: true,
					/* 背景 */
					bgColor: "#2979FF",
					/* 标题 （屏幕中心居中 两边图标中心居中使用slot center1） */
					navTitle: {
						text: "绑定传感器",
						color: "#ffffff",
						fontSize: "18px", // px upx rpx
						fontWeight: "500", // 100 - 700
					},
					isCustomFn: true,
					btnType: "type2",
					type2Config: {
						// 左图标
						leftPath: "/static/img/back.png",
						// 右图标
						rightPath: "/static/img/home.png",
						// 圆角
						radius: "40rpx",
					}
				},
				PhoneInfo: '',
				show: false,
				equipmentshow: false,
				equipmentcolumns: [],
				pointshow: false,
				pointcolumns: [],
				sensorinfo: {
					id: '',
					name: '',
					equipmentid: '',
					equipmentname: '',
					pointid: '',
					pointname: ''
				},
				userinfo: '',
				rules: {
					id: [{
						type: 'string',
						required: true,
						message: '请扫描传感器机身二维码或者直接输入SN',
						trigger: ['change', 'blur'],
					}],
					name: [{
						type: 'string',
						max: 20,
						message: '请为传感器设置便于记忆的别名',
						trigger: ['change', 'blur'],
					}, ],
					equipmentname: [{
						type: 'string',
						required: true,
						message: '请选择设备',
						trigger: ['change', 'blur'],
					}],
					pointname: [{
						type: 'string',
						required: true,
						message: '请选择测点',
						trigger: ['change', 'blur'],
					}]
				}
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules)
		},
		onLoad(parameter) {
			this.PhoneInfo = this.$utils.GetPhoneInfo();
			this.userinfo = uni.getStorageSync('userinfo');
			if (JSON.stringify(parameter) !== "{}") {
				this.sensorinfo.equipmentid = parameter.equipmentRealId
				this.sensorinfo.pointid = parameter.pointRealId
				this.show = true
			} else {
				this.show = false
			}
			this.geteqipmentlist()
		},
		methods: {
			geteqipmentlist() {
				//获取设备列表
				uni.request({
					url: getApp().globalData.serverAddress + this.$uri.Uri_getAllequipment
						.replace("{userRealId}",
							this.userinfo.userRealId),
					method: "GET",
					success: (res) => {
						if (res.statusCode !== 200) {
							this.$utils.showToast(this, '服务器错误,请联系技术支持人员!', 'error');
							return
						}
						if (this.show == false) {
							this.equipmentcolumns.push(res.data.data)
						} else {
							this.equipmentcolumns.push(res.data.data)
							for (let iteem of this.equipmentcolumns[0]) {
								if (iteem.equipmentRealId == this.sensorinfo.equipmentid) {
									this.sensorinfo.equipmentname = iteem.name
									for (let itm of iteem.points) {
										if (itm.pointRealId == this.sensorinfo.pointid) {
											this.sensorinfo.pointname = itm.name
										}
									}
								}
							}
						}
					}
				})
			},
			//返回
			onLeftClick() {
				uni.navigateBack({
					delta: 1
				});
			},
			//隐藏软键盘
			hideKeyboard() {
				uni.hideKeyboard()
			},
			//设备
			equipmentconfirm(e) {
				this.sensorinfo.equipmentname = e.value[0].name
				this.sensorinfo.equipmentid = e.value[0].equipmentRealId
				//选择设备以后清空上一次的测点id和名称以及列表
				this.sensorinfo.pointname = ""
				this.sensorinfo.pointid = ""
				this.pointcolumns = []
				for (let item of this.equipmentcolumns[0]) {
					if (item.equipmentRealId == this.sensorinfo.equipmentid) {
						this.pointcolumns.push(item.points)
					}
				}
				this.equipmentshow = false
				this.$refs.form1.validateField('equipmentname')
			},
			//测点
			pointconfirm(e) {
				this.sensorinfo.pointname = e.value[0].name
				this.sensorinfo.pointid = e.value[0].pointRealId
				this.pointshow = false
				this.$refs.form1.validateField('pointname')
			},
			//扫描二维码并且获取数据
			scanCode() {
				uni.scanCode({
					success: (res) => {
						this.sensorinfo.id = res.result
					},
					fail() {
						this.$utils.showToast(this, "扫码失败! ", 'error');
					}
				});
			},
			//绑定传感器
			add() {
				let sonsordata = new Object();
				sonsordata.DevicePrototypeRealId = this.sensorinfo.id;
				sonsordata.name = this.sensorinfo.name;
				sonsordata.PointRealId = this.sensorinfo.pointid;
				sonsordata.EquipmentRealId = this.sensorinfo.equipmentid;
				this.$refs.form1.validate().then(res => {
					uni.showLoading({
						title: "绑定中...",
						mask: true,
					});
					uni.request({
						url: getApp().globalData.serverAddress + this.$uri.Uri_addSensor.replace(
							"{userRealId}", this.userinfo.userRealId),
						data: JSON.stringify(sonsordata),
						dataType: "json",
						method: "POST",
						success: (res) => {
							if (res.statusCode !== 200) {
								this.$utils.showToast(this, '服务器错误,请联系技术支持人员!', 'error');
								return
							}
							if (res.data.code == 0) {
								this.$utils.showToast(this, '绑定成功！', 'success', 4,
									'/pages/sensor/sensorList?macCode=' + sonsordata
									.DevicePrototypeRealId);
							} else {
								this.$utils.showToast(this, res.data.msg, 'error');
							}
						},
						fail: (res) => {
							this.$utils.showToast(this, '绑定失败！', 'error');
						},
						complete: () => {
							uni.hideLoading();
						}
					})
				}).catch(errors => {
					this.$utils.showToast(this, '请填写正确的信息！', 'warning');
				})
			}
		}
	}
</script>

<style lang="scss">
	.u-form-item__body {
		padding: 15px 0 !important;
	}

	.u-form {
		width: 90%;
		margin: 10% auto;
	}

	.u-input {
		background-color: #fff !important;
	}

	.page {
		padding-top: 1%;
		margin: 5% auto;
		height: 85%;
		width: 90%;
		border-radius: 15px;
		background-color: #fff;
	}

	.saoma {
		width: 61%;
		height: 30%;
		margin: 10% auto;
		border-radius: 50%;
		border: 1px solid #2979ff;
		background-color: #2979ff;
	}

	.saom {
		width: 80%;
		height: 80%;
		margin: 10% auto;
		border-radius: 50%;
		border: 1px solid #2477eb;
		background-color: #2477eb;
	}

	.sao {
		width: 70%;
		height: 70%;
		margin: 15% auto;
		border-radius: 50%;
		border: 1px solid #2b85e4;
		background-color: #2b85e4;
	}

	.sa {
		width: 70%;
		height: 70%;
		margin: 15% auto;
		border-radius: 50%;
		border: 1px solid #3c9cff;
		background-color: #3c9cff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.button {
		width: 70%;
		margin: 15% auto;
	}
</style>